/**
 * class pineapple.PagingDevice
 *
 * March 28, 2012 
 * @authors Roman Kotusev, Darjuš Ilcevič, Kristis Vaškys
 */
package pineapple;
/**
 *
 * @author Ronny
 */

public class PagingDevice {

    private Memory memory;
    private boolean [] busy;

    public PagingDevice(Memory mem) {
        memory = mem;
        busy = new boolean[mem.getSize()];
    }

    public void reserveMemory(Processor proc) {
        int i = 0;
        int start = 0;                  // marks start of segment
        
        while (i < memory.getSize()) {
            if (busy[i] != true) {
                if (i - start == 63) {
                    proc.setPCS(start);
                    reserveMemory(start, i);
                    i++;
                    start = i;
                    break;
                }
                i++;
            }
            else {
                i++;
                start = i;
            }
        }
        
        while (i < memory.getSize()) {
            if (busy[i] != true) {
                if (i - start == 63) {                    
                    proc.setPDS(start);
                    reserveMemory(start, i);
                    i++;
                    start = i;
                    break;
                }
                i++;
            }
            else {
                i++;
                start = i;
            }
        }

        while (i < memory.getSize()) {
            if (busy[i] != true) {
                if (i - start == 63) {
                    proc.setPSS(start);
                    reserveMemory(start, i);
                    i++;
                    break;
                }
                i++;
            }
            else {
                i++;
                start = i;
            }
        }
    }
    
    public void reserveMemory(int start, int end){
        for (int i = start; i <= end; i++){
            busy[i] = true;
        }
    }

    public void clearMemory(Processor proc){
        int i;
        int PCS = proc.getPCS();
        int PDS = proc.getPDS();
        int PSS = proc.getPSS();
        
        System.out.println("CLEAR MEMORY");
        for (i = 0; i < 64; i++){
            busy[i+PCS] = false;
            memory.setNumber(null, i + PCS);
        }
        for (i = 0; i < 64; i++){
            busy[i+PDS] = false;
            memory.setNumber(null, i + PDS);
        } 
        for (i = 0; i < 64; i++){
            busy[i+PSS] = false;
            memory.setNumber(null, i + PSS);
        } 
    }
    
    public void clearMemory(int start, int end){
        for (int i = start; i <= end; i++){
            busy[i] = false;
            memory.setNumber(null, i);
        }
    }


    
}
